package com.globallogic.jira.gadget.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.issue.issuetype.IssueType;
import com.atlassian.jira.issue.link.IssueLinkType;
import com.atlassian.jira.issue.link.IssueLinkTypeManager;
import com.atlassian.jira.issue.priority.Priority;
import com.atlassian.jira.issue.resolution.Resolution;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.security.Permissions;
import com.atlassian.jira.security.roles.ProjectRoleManager;
import com.atlassian.jira.user.UserUtils;
import com.globallogic.jira.gadget.composite.IssueAction;
import com.globallogic.jira.gadget.utils.FormBuilder;

/**
 * <p/>
 * A servlet that perform dynamic generation of form in context menus with
 * dynamical options can be selected.
 */
@SuppressWarnings("serial")
public class FormGenerator extends HttpServlet {

	private final Logger log = Logger.getLogger(FormGenerator.class);
	private final ProjectRoleManager projectRoleManager = ComponentManager
			.getComponentInstanceOfType(ProjectRoleManager.class);
	private final PermissionManager permissionManager = ComponentAccessor
			.getComponent(PermissionManager.class);

	@Override
	protected void doPost(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		final String formType = req.getParameter("form_type");
		final String issueKey = req.getParameter("issue_key");
		final String projectName = req.getParameter("projectName");
		System.out.println(projectName);
		if (log.isInfoEnabled())
			log.info("\n*** Parameters from request: ***\n " + "\tForm type="
					+ formType + "\n\tIssue Key=" + issueKey);

		String result = "";
		switch (IssueAction.getValue(formType)) {
		case ADD:
			result = getAddForm(issueKey);
			break;
		case ASSIGN:
			result = getAssignForm(issueKey, projectName);
			break;
		case RESOLVE:
			result = getResolveForm(issueKey);
			break;
		case NONE:
			return;
		}

		final PrintWriter writer = resp.getWriter();
		writer.println(result);
		writer.flush();
		writer.close();

	}

	private String getAssignForm(final String issueKey, final String projectName) {
		final StringBuilder users = new StringBuilder();
		projectRoleManager.getProjectRoles();
		final Project project = ComponentManager.getInstance()
				.getProjectManager().getProjectObjByName(projectName);
		System.out.println(projectName);
		System.out.println(project);
		if (project == null)
			return "No project found";
		users.append("<select name=\"assignee\"  style=\"width:100%\">");
		for (final User user : UserUtils.getAllUsers()) {
			if (permissionManager.hasPermission(Permissions.ASSIGNABLE_USER,
					project, user))
				users.append("<option value=\"" + user.getName() + "\">"
						+ user.getName() + " - " + user.getEmailAddress()
						+ "</option>");
		}
		users.append("</select>");
		return new FormBuilder("assign").addField("Assignee", users.toString())
				.getForm();
	}

	private String getResolveForm(final String issueKey) {
		final ConstantsManager constantsManager = ComponentManager
				.getInstance().getConstantsManager();
		final Collection<Resolution> resolutions = constantsManager
				.getResolutionObjects();
		final StringBuilder resolutionSelect = new StringBuilder();
		resolutionSelect
				.append("<select name=\"resolution\" style=\"width:100%\">");
		for (final Resolution res : resolutions)
			resolutionSelect.append("<option value=\"" + res.getName() + "\">"
					+ res.getName() + "</option>");

		resolutionSelect.append("</select>");
		return new FormBuilder("resolve")
				.addField("Resolution", resolutionSelect.toString())
				.addField(
						"Time Spent",
						"<input type=\"text\" name=\"time_spent\"  style=\"width:100%\"><br/>(eg. 3w 4d 12h)")
				.getForm();
	}

	private String getAddForm(final String issueKey) {
		final ConstantsManager constantsManager = ComponentManager
				.getInstance().getConstantsManager();
		final IssueLinkTypeManager issueLinkTypeManager = ComponentManager
				.getComponentInstanceOfType(IssueLinkTypeManager.class);

		final StringBuilder issueTypeSelect = new StringBuilder();
		issueTypeSelect
				.append("<select name=\"issue_type\"  style=\"width:100%\">");
		for (final IssueType it : constantsManager.getAllIssueTypeObjects()) {
			issueTypeSelect.append("<option value=\"" + it.getName() + "\">"
					+ it.getName() + "</option>");
		}
		issueTypeSelect.append("</select>");
		final StringBuilder prioritySelect = new StringBuilder();
		prioritySelect
				.append("<select name=\"priority\"  style=\"width:100%\">");
		for (final Priority priority : constantsManager.getPriorityObjects()) {
			if (priority.getName().equals("Major"))
				prioritySelect.append("<option selected value=\""
						+ priority.getName() + "\">" + priority.getName()
						+ "</option>");
			else
				prioritySelect.append("<option value=\"" + priority.getName()
						+ "\">" + priority.getName() + "</option>");
		}
		prioritySelect.append("</select>");

		final StringBuilder linkTypeSelect = new StringBuilder();
		linkTypeSelect
				.append("<select name=\"link_type\"  style=\"width:100%\">");
		for (final IssueLinkType issueLinkType : issueLinkTypeManager
				.getIssueLinkTypes(true)) {
			linkTypeSelect.append("<option value=\"" + issueLinkType.getName()
					+ "\">" + issueLinkType.getName() + "</option>");
		}
		linkTypeSelect.append("</select>");
		return new FormBuilder("add")
				.addField("Issue type", issueTypeSelect.toString())
				.addField("Priority", prioritySelect.toString())
				.addField("Link type", linkTypeSelect.toString())
				.addField("Summary",
						"<textarea rows=\"5\" cols=\"10\" name=\"summary\"  style=\"width:100%\"/>")
				.getForm();
	}
}